<template>
    <div class="allout" v-if="indexList.length">
        <headbar title="选择城市" 
        :right="false" 
        :left="true" 
        classleft="el-icon-back"
        @handleleft="toback"></headbar>

        <div class="mar">
            <van-index-bar :index-list="indexList">
                <span v-for="item in cell" :key="item.firstword" >
                    <van-index-anchor :index="item.firstword">{{ item.firstword }}</van-index-anchor>
                    <van-cell v-for="(city,index) in item.city" :key="index" :title="city.name" @click="changecity(city.name)"/>
                </span>
            </van-index-bar>
        </div>
        
    </div>
</template>

<script>
import axios from 'axios'
import headbar from '@/components/headbar.vue'
export default {
    components:{
        headbar
    },
    mounted(){
        axios('http://localhost:3000/cities').then(res=>{
            console.log(res.data)
            this.citylist = res.data
            for(let i = 65;i<91;i++){
                var obj = {city:[]}
                this.citylist.forEach(item => {
                    if(item.pinyin.charAt(0).toUpperCase() === String.fromCharCode(i)){
                        obj.firstword = String.fromCharCode(i)
                        obj.city.push(item)
                    }
                })

                if(obj.city.length != 0){
                    this.cell.push(obj)
                }
            }
            for(let i = 65;i<91;i++){
                for(let j=0;j<this.cell.length;j++){
                    if(this.cell[j].firstword.charCodeAt(0) === i){
                        this.indexList.push(this.cell[j].firstword)
                    }
                }
            }
        })
    },
    data(){
        return{
            citylist:[],
            cell:[],
            indexList:[]
        }
    },
    methods:{
        toback(){
            this.$router.back()
        },
        changecity(city){
            this.$store.commit('changeCity',city)
            this.$router.push('/home')
        }
    }
}
</script>

<style lang="scss" scoped>
.allout{
    margin-bottom: 0.55rem;
}
</style>